HashMap = function(){  
    this.map = new Array();
};  
HashMap.prototype = {  
    put : function(key, value){  
        this.map[key] = value;
    },  
    get : function(key){  
        return this.map[key];
    },  
    getAll : function(){  
        return this.map;
    },  
    clear : function(){  
        this.map = new Array();
    },  
    getKeys : function(){  
        var keys = new Array();  
        for(i in this.map){  
            keys.push(i);
        }  
        return keys;
    }
};

window.onload = function() {
	var dataStore = new HashMap();
	
	dhtmlx.image_path = contextPath + '/resources/common/js/dhtmlx_std_full/imgs/';
	
	var main_layout = new dhtmlXLayoutObject(document.body, '2U');

	var a = main_layout.cells('a');
	
	var tabbar_1 = a.attachTabbar();
	tabbar_1.addTab('tab_1', 'DEVICE', '90');
	tabbar_1.addTab('tab_2', '정보', '90');
	var tab_1 = tabbar_1.cells('tab_1');
	tabbar_1.setTabActive('tab_1');
	var tab_2 = tabbar_1.cells('tab_2');

	var b = main_layout.cells('b');
	b.setWidth('1000');
	b.setHeight('700');

	var layout_1 = b.attachLayout('4U');

	var cell_1 = layout_1.cells('a');
	cell_1.setText('INFO');
	cell_1.setHeight('200');

	var cell_2 = layout_1.cells('b');
	cell_2.setText('LOCATION');

	var cell_3 = layout_1.cells('c');
	cell_3.setText('REQUEST LOG');

	var c = layout_1.cells('d');

	var layout_2 = c.attachLayout('2E');
	
//----------------------------------- Chart 검색 관련 부분 -----------------------------------------------------
	
	var cell_5 = layout_2.cells('a');
	cell_5.setText('CHART');
	layout_2.attachEvent('onDblClick', function (itemId) {
		$(function() {
//			$( "#menu" ).menu();
//		    $( "#dialog" ).dialog();
		});
		if ( itemId == 'a' ) {
			var dhxWins= new dhtmlXWindows();

			var chartWin = dhxWins.createWindow('chartSubWin', 205, 160, 460, 80);
			//chartWin.attachLayout('1C');
			chartWin.setText('검색');
//			chartWin.button("close").show();  
			chartWin_formData = [ { type:'settings', labelWidth:80, inputWidth:250, position:'absolute'  },
				              	  { type:'label', name:'label_from', label:'From', width:75, labelWidth:75, labelAlign:'left', labelLeft:5, labelTop:8  },
				              	  { type:'calendar', name:'calendar_from', inputWidth:120, dateFormat: '%Y-%m-%d %H:%i', enableTime: true, inputLeft:50, inputTop:10  },
				            	  { type:'label', name:'label_to', label:'To', width:75, labelWidth:75, labelAlign:'left', labelLeft:190, labelTop:8  },
				            	  { type:'calendar', name:'calendar_to', inputWidth:120, dateFormat: '%Y-%m-%d %H:%i', enableTime: true, inputLeft:220, inputTop:10  },
				            	  { type:'button', name:'search', label:'검색', value:'검색', inputWidth:100, inputLeft:360, inputTop:8  } ];

			var chartWin_form = chartWin.attachForm(chartWin_formData);
			chartWin_form.attachEvent('onButtonClick', function(name){
				if ( name == 'search' ) {
					var fromDateValue 	= chartWin_form.getInput('calendar_from').value;
					var toDateValue 	= chartWin_form.getInput('calendar_to').value;
					var id 				= dataStore.get('chartId');

					console.log(id);
					createChart(id, 10, fromDateValue + ':00', toDateValue + ':00');
					dhxWins.window("chartSubWin").close();
				}
			});
		}
	});
		
	var cell_6 = layout_2.cells('b');
		cell_6.setText('TABLE');
//-----------------------------------------------------------------------------------------------------
		
//------------------------- menu bar 관련 부분 ----------------------------------------------------------
	var menu_1 = main_layout.attachMenu();
		menu_1.setIconsPath(contextPath + '/resources/common/js/dhtmlx_std_full/imgs/');
		menu_1.addNewSibling(null, 'A', 'File');
		menu_1.addNewSibling(null, 'B', 'Login'); //아이디로 알파벳 순 정렬 
		
		menu_1.addNewChild('File', 0, 'New', 'New');
		menu_1.addNewChild('File', 1, 'Logout', 'Logout');
		menu_1.addNewChild('File', 2, 'Close', 'Close');

//------------------------------------------------------------------------------------------------------

//------------------------- 트리 관련 부분 -----------------------------------------------------------------	
	var tree_1 = tab_1.attachTree();
		tree_1.setIconsPath(contextPath + '/resources/common/js/dhtmlx_std_full/imgs/');
		tree_1.enableTreeImages(false);
		tree_1.insertNewChild(0, 'root', 'NETWORK');
		
		var tableRequest = $.ajax({
			url : '/bwf/device/',
			type : 'GET',
			dataType : 'json'
		});
		tableRequest.done(function(info) {
			for ( var i = 0; i < info.length; i++ ) {
				data = info[i];
				dataStore.put(data['id'], data);
				tree_1.insertNewChild('root', data['id'], data['name']);
			}
		});
		tableRequest.fail(function(jqXHR, textStatus) {
			alert('Request failed!');
		});
		
		tree_1.attachEvent('onSelect', function(id) {
			console.log('tree selected id : ' + id);
			var selectedData = dataStore.get(id);
			
			product  = tree_1.getItemText(id);
			seNum	 = id;  
			actiCode = '@12ab' + id;
			
			createMarker(id);
			createTable(id);
			createRequestLog();
			setFormValue(product, seNum, actiCode);
			
			setInfoValue(selectedData['name'], selectedData['longitude'], selectedData['latitude']);
		});
	
//-----------------------------------------------------------------------------------------------------------
// 라벨 에서 ID :  이부분을  ID  (공백) : 채우는 방법 물어보기.
//------------------------- DEVICE 정보 관련 부분 --------------------------------------------------------------------
	var deviceFormData = [ { type:'settings', labelWidth:80, inputWidth:250, position:'absolute' },
			     		   { type:'label', name:'nameLabel', label:'Name : ', width:125, labelWidth:125, labelAlign:'left', labelLeft:20, labelTop:25  },
			     		   { type:'label', name:'longitudeLabel', label:'Longitude : ', width:125, labelWidth:125, labelAlign:'left', labelLeft:20, labelTop:55  },
			     		   { type:'label', name:'latitudeLabel', label:'Latitude : ', width:125, labelWidth:125, labelAlign:'left', labelLeft:20, labelTop:85  },
			     		   { type:'label', name:'name', labelAlign:'left', labelWidth:150, labelLeft:120, labelTop:25  },
			     		   { type:'label', name:'longitude', labelAlign:'left', labelWidth:150, labelLeft:120, labelTop:55  },
			     		   { type:'label', name:'latitude', labelAlign:'left', labelWidth:150, labelLeft:120, labelTop:85  } ];
	
	var deviceInfoForm = tab_2.attachForm(deviceFormData);
	
	function setInfoValue(name, longitude, latitude) {
		deviceInfoForm.setItemLabel('name', product);
		deviceInfoForm.setItemLabel('longitude', longitude);
		deviceInfoForm.setItemLabel('latitude', latitude);
	}
		
//-----------------------------------------------------------------------------------------------------------
		
//------------------------- FORM 관련 부분 --------------------------------------------------------------------		
	var formData = [ { type:'settings' , labelWidth:80, inputWidth:250, position:'absolute' },
	     			 { type:'label', name:'productLabel', label:'Product : ', width:125, labelWidth:125, labelAlign:'left', labelLeft:40, labelTop:25  },
	     			 { type:'label', name:'serialLabel', label:'Serial Number : ', width:125, labelWidth:125, labelAlign:'left', labelLeft:40, labelTop:55  },
	     			 { type:'label', name:'activationCodeLabel', label:'Activation Code : ', width:125, labelWidth:125, labelAlign:'left', labelLeft:40, labelTop:85  },
	     			 { type:'label', name:'product', labelAlign:'left', labelWidth:150, labelLeft:180, labelTop:25  },
	     			 { type:'label', name:'serialNumber', labelAlign:'left', labelWidth:150, labelLeft:180, labelTop:55  },
	     			 { type:'label', name:'activationCode', labelAlign:'left', labelWidth:150, labelLeft:180, labelTop:85  } ];
	var form = cell_1.attachForm(formData);
		form.attachEvent('onButtonClick', function(id){
			if ( id == 'update' ) {
				id 		= form.getItemValue('serialNumber');
				name 	= form.getItemValue('product');
				
				tree_1.setItemText(id, name);
			}
		});
	function setFormValue(product, seNum, actiCode) {
		form.setItemLabel('product', product);
		form.setItemLabel('serialNumber', seNum);
		form.setItemLabel('activationCode', actiCode);
	}
//-----------------------------------------------------------------------------------------------------------	

//------------------------- LOCATION 관련 부분 -----------------------------------------------------------------
	var customparams = {
		center : new google.maps.LatLng(36, -232),
		zoom : 7,
		mapTypeId : google.maps.MapTypeId.ROADMAP
	};
	var GMaps = layout_1.cells('b').attachMap(customparams);
	
	function createMarker(id) {
		var markerRequest = $.ajax({
			url : '/bwf/device/' + id,
			type : 'GET',
			dataType : 'json'
		});
		markerRequest.done(function(info) {
			marker = new google.maps.Marker({
				map : GMaps,
				position : new google.maps.LatLng(parseInt(info['latitude']),
						parseInt(info['longitude'])),
				draggable:true, // Bounce
				animation: google.maps.Animation.DROP // Bounce 
			});
			var infowindow = new google.maps.InfoWindow({
				content : info['name']
			});

			google.maps.event.addListener(marker, 'click', function() {
				infowindow.close(GMaps, marker);
			});
			infowindow.open(GMaps, marker);
		});
		markerRequest.fail(function(jqXHR, textStatus) {
			alert('Request failed!');
		});
	}
//-------------------------------------------------------------------------------------------------------------
	
//------------------------- REQUEST LOG 관련 부분 ----------------------------------------------------------------	
	var grid_2 = cell_3.attachGrid();
		grid_2.setIconsPath(contextPath + '/resources/common/js/dhtmlx_std_full/imgs/');
	
		grid_2.setHeader('METHOD, URL, RESULT, TIME');
		grid_2.setInitWidths('60, 100, 60, 125');
		grid_2.setColAlign('center, left, center, left');
		grid_2.setColSorting('int, int, str, date');
		grid_2.init();

	function createRequestLog() {
		grid_2.clearAll();
		grid_2.addRow(1, ['GET', '/channel', 'OK', '2014-05-28 11:00:00'], 1);
		grid_2.addRow(2, ['POST', '/channel', 'OK', '2014-05-28 12:00:30'], 2);
		grid_2.addRow(3, ['GET', '/channel', 'NOK', '2014-05-28 12:05:00'], 3);
		grid_2.addRow(4, ['POST', '/channel', 'OK', '2014-05-28 15:25:30'], 4);
	}
		
//-------------------------------------------------------------------------------------------------------------
		
//------------------------- CHART 관련 부분 ---------------------------------------------------------------------			
	var chart_2 = cell_5.attachChart({
		view 		: 'spline', //spline = 곡선, line = 직선
		container 	: 'chart_container',
		value 		: '#curVal#',
		label 		: '#eventTime#',
		tooltip 	: '#eventTimeFull#',
		item 		: { borderColor : '#ffffff',
							color 	: '#000000' },
		line 		: { color 		: '#ff9900',
						width 		: 2 },
		xAxis 		: { title 		: 'EventTime',
						template 	: '#eventTime#',
						},
		yAxis 		: { title : 'Current Values' },
	});
	
	function createChart(id, count, startTime, endTime) {
		chart_2.clearAll();
		dataStore.put('chartId', id);
		dataStore.put('chartCount', count);
		
		var tableRequest = $.ajax({
			url : '/bwf/channel_history/' + id + '?count=' + count + '&startTime=' + startTime + '&endTime=' + endTime, 
			type : 'GET',
			dataType : 'json',
		});
		tableRequest.done(function(info) {
//			chart_2.parse(info, 'json');
			
			var chartData = [];
			var count = info.length;
			
			for ( var i = count - 1; i >= 0; i -- ) {
				data = info[i];	
				
				var dateTime = new Date(data['eventTime']);
				dateTimeFormat = dateTime.getMinutes() + ':' + dateTime.getSeconds();
				chartData.push({ eventTime : dateTimeFormat , curVal : data['curVal'], eventTimeFull : data['eventTime'] });
			}
			
			chart_2.parse(chartData, 'json');
		});
		tableRequest.fail(function(jqXHR, textStatus) {
			alert('Request failed!');
		});
	}
//-------------------------------------------------------------------------------------------------------------
	
	var grid_1 = cell_6.attachGrid();
		grid_1.setIconsPath(contextPath + '/resources/common/js/dhtmlx_std_full/imgs/');
	
		grid_1.setHeader('ID, DEVICE ID, NAME, MAX_VAL, MIN_VAL');
		grid_1.setInitWidths('100, 100, 450, 200, 200');
		grid_1.setColAlign('left, left, left, left, left');
		grid_1.setColSorting('int, int, str, int, int');
		grid_1.init();
		
		grid_1.attachEvent('onRowSelect', function(id, ind){
			var selId = grid_1.getCombo(id);
			console.log(selId);
			createChart(id, 10, '2014-05-28 13:29:15', '2014-05-28 13:30:15');
		});
		
	function createTable(id) {
		grid_1.clearAll();
		var tableRequest = $.ajax({
			url : '/bwf/channel/' + id,
			type : 'GET',
			dataType : 'json'
		});
		tableRequest.done(function(info) {
			for ( var i = 0; i < info.length; i++ ) {
				data = info[i];
				console.log(data);
				grid_1.addRow(i, [ data['deviceId'], data['id'], data['name'], data['maxVal'], data['minVal'] ], i);	
			}
		});
		tableRequest.fail(function(jqXHR, textStatus) {
			alert('Request failed!');
		});
	}	
};
